﻿using System;
using System.Web.UI.WebControls;
using jeward.core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace jeward.changemasterpage
{
    public partial class chngmp : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblCrntmp.Text = Web.MasterUrl.Substring(Web.MasterUrl.LastIndexOf('/') + 1);
                FillDropDownList();
            }
        }

        #region Controls
        protected void btnChange_Click(object sender, EventArgs e)
        {
            ViewState["ddlmpSelectedIndex"] = ddlmp.SelectedIndex;
            string url = ddlmp.SelectedValue;
            Change(url);
            FillDropDownList();
            if (ViewState["ddlmpSelectedIndex"] != null)
                ddlmp.SelectedIndex = Convert.ToInt32(ViewState["ddlmpSelectedIndex"]);
            lblCrntmp.Text = Web.MasterUrl.Substring(Web.MasterUrl.LastIndexOf('/') + 1);
            hdnResult.Value = "success";
            hdnComeout.Value = "Master Page has Changed!";
        }

        protected void btnSync_Click(object sender, EventArgs e)
        {
            Sync();
            FillDropDownList();
            hdnResult.Value = "success";
            hdnComeout.Value = "Master Page has Synced!";
        }
        #endregion

        #region Actions
        private bool Sync()
        {
            bool result = false;
            try
            {
                if (!Web.IsRootWeb)
                {
                    SPWeb rootWeb = Web.Site.RootWeb;
                    SPList rootList = rootWeb.Lists["Master Page Gallery"];
                    SPList list = Web.Lists["Master Page Gallery"];
                    foreach (SPListItem rItem in rootList.Items)
                    {
                        SPFile file = Web.GetFile(list.RootFolder.Url + "/" + rItem["FileLeafRef"]);
                        if (!file.Exists)
                        {
                            SPFile rootFile = rootWeb.GetFile(rootList.RootFolder.Url + "/" + rItem["FileLeafRef"]);
                            if (rootFile.Exists)
                            {
                                byte[] rootFileByte = rootFile.OpenBinary();
                                Web.AllowUnsafeUpdates = true;
                                Web.Files.Add(list.RootFolder.Url + "/" + rItem["FileLeafRef"], rootFileByte, true);
                            }
                        }
                    }
                    result = true;
                }
            }
            catch (Exception ex)
            {
                JWLog.WriteError("ChangeMasterPage", ex);
            }
            return result;
        }

        private bool Change(string _url)
        {
            bool result = false;
            try
            {
                Web.AllowUnsafeUpdates = true;
                Web.MasterUrl = _url;
                Web.Update();
                result = true;
            }
            catch (Exception ex)
            {
                JWLog.WriteError("ChangeMasterPage", ex);
            }
            return result;
        }
        #endregion

        #region Private
        private void FillDropDownList()
        {
            ddlmp.Items.Clear();
            SPList list = Web.Lists["Master Page Gallery"];
            foreach (SPListItem item in list.Items)
            {
                ListItem listItem = new ListItem(item["FileLeafRef"].ToString(), item["FileRef"].ToString());
                ddlmp.Items.Add(listItem);
            }
        }
        #endregion

        #region Ribbon
        private string ribbonTab = @"
          <Tab Id=""jwRibbon.Tab1"" Sequence=""400"" Description="""" Title=""Master Page"">
            <Scaling Id=""jwRibbon.Scaling"">
              <MaxSize Id=""jwRibbon.MaxSize1"" Sequence=""10"" GroupId=""jwRibbon.Group1"" Size=""LargeLarge""/>
              <Scale Id=""jwRibbon.Scale1"" Sequence=""20"" GroupId=""jwRibbon.Group1"" Size=""Popup"" />
            </Scaling>
            <Groups Id=""jwRibbon.Groups1"">
              <Group Id=""jwRibbon.Group1""
                     Sequence=""10"" 
                     Description=""""
                     Title=""Operation""
                     Image32by32Popup=""/_layouts/1033/images/formatmap32x32.png"" Image32by32PopupTop=""-416"" Image32by32PopupLeft=""-256""
                     Template=""Ribbon.Templates.Flexible2"" >
                <Controls Id=""jwRibbon.Controls.MasterPage"">
                  <Button
                    Id=""jwRibbon.Button1""
                    Sequence=""10""
                    Command=""jwRibbon.Command1""
                    Image32by32=""/_layouts/1033/images/formatmap32x32.png"" Image32by32Top=""-320"" Image32by32Left=""-128""
                    LabelText=""Change""
                    ToolTipTitle=""Change""
                    ToolTipDescription=""Change the selected master page.""
                    TemplateAlias=""o1""/>
                <Button
                    Id=""jwRibbon.Button2""
                    Sequence=""20""
                    Command=""jwRibbon.Command2""
                    Image32by32=""/_layouts/1033/images/formatmap32x32.png"" Image32by32Top=""-448"" Image32by32Left=""-224""
                    LabelText=""Sync""
                    ToolTipTitle=""Sync""
                    ToolTipDescription=""Sync master pages from root site.""
                    TemplateAlias=""o1""/>
                <Button
                    Id=""jwRibbon.Button3""
                    Sequence=""30""
                    Command=""jwRibbon.Command3""
                    Image32by32=""/_layouts/1033/images/formatmap32x32.png"" Image32by32Top=""-448"" Image32by32Left=""-288""
                    LabelText=""Close""
                    ToolTipTitle=""Close""
                    ToolTipDescription=""Close the modal modal dialog.""
                    TemplateAlias=""o1""/>
                </Controls>
              </Group>
            </Groups>
          </Tab>";

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            var cmds = new System.Collections.Generic.List<IRibbonCommand>();

            cmds.Add(new SPRibbonCommand("jwRibbon.Command1", "chngmp_Change_Click('" + btnChange.ClientID + "')", "true"));
            cmds.Add(new SPRibbonCommand("jwRibbon.Command2", "chngmp_Sync_Click('" + btnSync.ClientID + "')", (!Web.IsRootWeb).ToString().ToLower()));
            cmds.Add(new SPRibbonCommand("jwRibbon.Command3", "chngmp_Close_Click()", "true"));

            JWRibbon.SetRibbon(Page, ribbonTab, "jwRibbon.Tab1", cmds);
        }
        #endregion
    }
}
